/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import {Meteor} from 'meteor/meteor';
import '../imports/api/users/users.js';
import '../imports/api/methods.js';
import {buildWS} from '../imports/api/repchainWebsocketHelper'
import setting from '../setting.js';
import fs from 'fs';
import path from 'path';
import uuidv1 from 'uuid/v1';
import {WebApp} from 'meteor/webapp';

const setting_path = new setting();

Meteor.startup(() => {
    // code to run on server at startup

    // Praper directories the app need
    if (!fs.existsSync(setting_path.prvkey_file_location))
        fs.mkdirSync(setting_path.prvkey_file_location);
    if (!fs.existsSync(setting_path.pic_root))
        fs.mkdirSync(setting_path.pic_root);
    if (!fs.existsSync(setting_path.pic_root + path.sep + setting_path.pic_upload))
        fs.mkdirSync(setting_path.pic_root + path.sep + setting_path.pic_upload);
    // The Current only one user
    CurUser = 'none';

    //current user is admin?
    isAdmin = false;

    //long connection with repchain
    buildWS();



    // To store uploading pictures into a local directory
    WebApp.connectHandlers.use('/' + setting_path.pic_upload, (req, res, next) => {
        let unique_name = uuidv1() + '.jpg';
        let file_path = path.join(setting_path.pic_root, setting_path.pic_upload, unique_name);
        let file_w_stream = fs.createWriteStream(file_path);
        file_w_stream.on('error', (error) => console.log(error));
        file_w_stream.on('finish', () => {
            res.writeHead(200, {
                "Access-Control-Allow-Origin": "*",
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Methods': '*'
            });
            res.write(unique_name);
            res.end();
        });
        req.pipe(file_w_stream);
    });

    // To response a requested picture
    WebApp.connectHandlers.use('/pic', (req, res, next) => {
        let file_name = path.join(setting_path.pic_root, setting_path.pic_upload, req._parsedUrl.query);
        let file_rs = fs.createReadStream(file_name);
        res.writeHead(200, {
            'Content-Type': 'image/jpeg',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Methods': '*'
        });
        file_rs.on('data', (chunk) => res.write(chunk));
        file_rs.on('end', () => res.end())
    });

});
